package cn.topcodes.tcsf.app.web.controller.api;

import cn.topcode.unicorn.utils.*;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.service.SysFileService;
import cn.topcodes.tcsf.app.domain.api.*;
import cn.topcodes.tcsf.app.domain.entity.AppUser;
import cn.topcodes.tcsf.app.service.AppUserService;
import cn.topcodes.tcsf.app.web.controller.api.interceptor.IgnoreAppAuth;
import cn.topcodes.tcsf.app.web.controller.api.protocol.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * @author Unicorn
 * @date 2017/5/5
 */
@Api(tags = {"APP通用接口(账号)"})
@RestController
@RequestMapping(value = "/api/app/account", produces = "application/json")
public class AppUserApi {

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private SysFileService fileService;

    @IgnoreAppAuth
    @ApiOperation("账号注册")
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public ApiResponseEntity register(
            @Valid @RequestBody ReqRegister reqRegister,
            BindingResult result
    ) {
        ValidationUtil.validate(result);
        //  若姓名为空，则默认填用户名
        if(StringUtil.isBlank(reqRegister.getRealname())) {
            reqRegister.setRealname(reqRegister.getUsername());
        }
        this.appUserService.register(reqRegister.getUsername(), reqRegister.getPassword(), reqRegister.getRealname());
        return ApiResponseEntity.buildOK();
    }

    @IgnoreAppAuth
    @ApiOperation("账号登录")
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public ApiResponseEntity login(
            @Valid @RequestBody ReqLogin reqLogin,
            BindingResult result
    ) {
        ValidationUtil.validate(result);
        String token = this.appUserService.login(reqLogin.getUsername(), reqLogin.getPassword(), reqLogin.getAppClient());
        AppUser appUser = this.appUserService.findByUsername(reqLogin.getUsername());
        RespLogin respLogin = new RespLogin();
        respLogin.setToken(token);
        respLogin.setUsername(appUser.getUsername());
        respLogin.setEmail(appUser.getEmail());
        respLogin.setGender(appUser.getGender());
        respLogin.setTel(appUser.getTel());
        respLogin.setRole(appUser.getRole());
        respLogin.setRealname(appUser.getRealName());
        //  处理地址 TODO
        respLogin.setHeadImgUrl(appUser.getHeadImgUrl());
        return ApiResponseEntity.buildOK(respLogin);
    }
//
//    @ApiOperation("第三方登录")
//    @RequestMapping(value = "third-party-login",method = RequestMethod.POST)
//    public ApiResponseEntity thirdPartyLogin(
//        @Valid @RequestBody ReqThirdPartyLogin req
//    ) {
//
//        String token = this.appUserService.login(reqLogin.getUsername(), reqLogin.getPassword(), reqLogin.getAppClient());
//        AppUser appUser = this.appUserService.findByUsername(reqLogin.getUsername());
//        RespLogin respLogin = new RespLogin();
//        respLogin.setToken(token);
//        respLogin.setUsername(appUser.getUsername());
//        respLogin.setEmail(appUser.getEmail());
//        respLogin.setGender(appUser.getGender());
//        respLogin.setTel(appUser.getTel());
//        respLogin.setRole(appUser.getRole());
//        respLogin.setRealname(appUser.getRealName());
//        //  处理地址 TODO
//        respLogin.setHeadImgUrl(appUser.getHeadImgUrl());
//        return ApiResponseEntity.buildOK(respLogin);
//    }

    @ApiOperation("账号退出")
    @RequestMapping(value = "logout",method = RequestMethod.POST)
    public ApiResponseEntity logout(
            @RequestHeader String token,
            @RequestParam(required = false) String app
    ) {
        if(StringUtil.isNotBlank(app)) {
            this.appUserService.logout(app, token);
        }else {
            this.appUserService.logout(token);
        }
        return ApiResponseEntity.buildOK();
    }

    @ApiOperation("修改个人账号信息")
    @RequestMapping(value = "personal-info",method = RequestMethod.POST)
    public ApiResponseEntity setAccountInfo(
            @RequestHeader String token,
            @Valid @RequestBody ReqModifyAccountInfo req,
            BindingResult result
    ) {
        ValidationUtil.validate(result);
        AppUser appUser = this.appUserService.findByToken(token);
        appUser.setRealName(req.getRealname());
        appUser.setGender(req.getGender());
        appUser.setTel(req.getTel());
        appUser.setEmail(req.getEmail());
        this.appUserService.update(appUser);
        return ApiResponseEntity.buildOK();
    }

    @ApiOperation("获取个人账号信息")
    @RequestMapping(value = "personal-info",method = RequestMethod.GET)
    public ApiResponseEntity getAccountInfo(
            @RequestHeader String token
    ) {
        UserInfo userInfo = new UserInfo();
        AppUser appUser = this.appUserService.findByToken(token);
        userInfo.setUsername(appUser.getUsername());
        userInfo.setEmail(appUser.getEmail());
        userInfo.setGender(appUser.getGender());
        // 处理头像地址 TODO
        userInfo.setHeadImgUrl(appUser.getHeadImgUrl());
        userInfo.setTel(appUser.getTel());
        userInfo.setRole(appUser.getRole());
        userInfo.setRealname(appUser.getRealName());
        Boolean needPerfect = this.appUserService.getAppUserParamValue(appUser.getId(), "needPerfect", Boolean.class, false);
        userInfo.setNeedPerfect(needPerfect);
        return ApiResponseEntity.buildOK().setBody(userInfo);
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "modify-password",method = RequestMethod.POST)
    public ApiResponseEntity modifyPassword(
            @RequestHeader String token,
            @Valid @RequestBody ReqModifyPassword req,
            BindingResult result
    ) {
        ValidationUtil.validate(result);
        AppUser appUser = this.appUserService.findByToken(token);
        this.appUserService.modifyPassword(appUser.getId(), req.getOldPwd(), req.getNewPwd());
        return ApiResponseEntity.buildOK();
    }

    @IgnoreAppAuth
    @ApiOperation("找回密码")
    @RequestMapping(value = "find-password",method = RequestMethod.POST)
    public ApiResponseEntity forgetPassword(
            @Valid @RequestBody FindPassword findPassword,
            BindingResult result
    ) {
        ValidationUtil.validate(result);
        AppUser appUser = this.appUserService.findByUsername(findPassword.getUsername());
        //  TODO 验证码验证
        this.appUserService.resetPassword(appUser.getId(), findPassword.getPassword());
        return ApiResponseEntity.buildOK();
    }

    @ApiOperation("设置语言")
    @RequestMapping(value = "set-language",method = RequestMethod.POST)
    public ApiResponseEntity setLanguage(
            @RequestHeader String token,
            @RequestBody ReqSetLanguage req,
            BindingResult result
            ) {
        ValidationUtil.validate(result);
        AppUser appUser = this.appUserService.findByToken(token);
        if(StringUtil.isBlank(req.getApp())) {
            this.appUserService.setLanguage(appUser.getId(), req.getLanguage());
        }else {
            this.appUserService.setLanguage(req.getApp(), appUser.getId(), req.getLanguage());
        }
        return ApiResponseEntity.buildOK();
    }

    @ApiOperation("心跳")
    @RequestMapping(value = "heartbeat", method = RequestMethod.POST)
    public ApiResponseEntity<RespHeartbeat> heartbeat(
            @RequestHeader String token,
            @Valid @RequestBody Heartbeat heartbeat,
            BindingResult result
            ) {
        ValidationUtil.validate(result);
        AppUser appUser = this.appUserService.findByToken(token);
        if(StringUtil.isNotBlank(heartbeat.getApp())) {
            this.appUserService.active(heartbeat.getApp(), appUser.getId());
        }else {
            this.appUserService.active(appUser.getId());
        }
        RespHeartbeat resp = new RespHeartbeat();
        resp.setHeartbeatInterval(1800);
        return ApiResponseEntity.buildOK(resp);
    }

    @ApiOperation("设置头像")
    @RequestMapping(value = "set-head-img",method = RequestMethod.POST)
    public ApiResponseEntity headImg(
            @RequestHeader String token,
            MultipartFile file) {

//        File targetFile = new File(path);
//        file.transferTo();
        return ApiResponseEntity.buildOK();
    }

    @IgnoreAppAuth
    @ApiOperation("发送找回密码验证")
    @RequestMapping(value = "send-find-pwd-verify",method = RequestMethod.POST)
    public ApiResponseEntity sendFindPwdVerify(
            @Valid @RequestBody SendFindPwdVerify sendFindPwdVerify, BindingResult result
    ) {
        ValidationUtil.validate(result);
        //  处理逻辑
        return ApiResponseEntity.buildOK();
    }

    /**
     * 获取头像
     * @param id
     * @return
     */
    @IgnoreAppAuth
    @ApiIgnore
    @RequestMapping(value = "get-head-img",method = RequestMethod.GET)
    public void headImg(
            @RequestParam Long id,
            HttpServletResponse response
    ) throws IOException {
        AppUser appUser = this.appUserService.findOne(id);
        if(appUser == null) {
            response.sendError(404);
        }


    }
}
